#include "Component.hpp"
TTF_Font* Component::default_font=nullptr;
Component::~Component()
{
    for(Component* com:children){
        delete com;
    }
    children.clear();
}

int Component::update(float delta)
{
    return 0;
}

void Component::render(SDL_Renderer* render)
{
    for(Component* com:children){
        com->render(render);
    }
}

int Component::handleEvent(SDL_Event &evt)
{
    for(Component* com:children){
        com->handleEvent(evt);
    }
    if(evt.type==SDL_MOUSEMOTION){
        if(Component::isInRect(this->abs_rect,evt.motion.x,evt.motion.y)){
            if(!this->inRect){
                this->mouseEnter(evt.motion);
                this->inRect=true;
                return 1;
            }else{
                this->mouseHover(evt.motion);
                return 1;
            }
        }else if(this->inRect){
                this->mouseLeave(evt.motion);
                this->inRect=false;
                return 1;
        }
    }else if(evt.type==SDL_MOUSEBUTTONDOWN && this->inRect){
        if(evt.button.button==SDL_BUTTON_LEFT){
            if(evt.button.clicks==2){
                this->mouseDbClick(evt.button);
                this->pressed = true;
                return 1;
            }else{
                this->mousePress(evt.button);
                this->pressed = true;
                return 1;
            }
        }
    }else if(evt.type==SDL_MOUSEBUTTONUP && this->inRect){
        if(this->pressed){
            this->mouseClick(evt.button);evt.button;
            this->pressed=false;
            this->mouseRelease(evt.button);
            return 1;
        }
    }
    return 0;
}

void Component::setPosition(int x, int y)
{
    this->abs_rect.x=x;
    this->abs_rect.y=y;
}

const SDL_Rect & Component::getRect() 
{
    return this->abs_rect;
}

void Component::setFont(TTF_Font *font)
{
    this->font = font;
}

void Component::setDefaultFont(TTF_Font *font)
{
    Component::default_font = font;
}

const TTF_Font *Component::getFont()
{
    return this->font==nullptr?Component::default_font:this->font;
}

bool Component::isInRect(SDL_Rect &rc, int x, int y)
{
    if(x<rc.x || x>= rc.x+rc.w || y< rc.y || y>= rc.y+rc.h) return false;
    return true;
}

void Component::mouseHover(SDL_MouseMotionEvent &evt)
{
    //SDL_Log("hover");
}

void Component::mouseEnter(SDL_MouseMotionEvent &evt)
{
    SDL_Log("enter");
}

void Component::mouseLeave(SDL_MouseMotionEvent &evt)
{
    SDL_Log("leave");
}

void Component::mouseClick(SDL_MouseButtonEvent &evt)
{
    SDL_Log("click");
}

void Component::mousePress(SDL_MouseButtonEvent &evt)
{
    SDL_Log("press");
}

void Component::mouseRelease(SDL_MouseButtonEvent &evt)
{
    SDL_Log("release");
}

void Component::mouseDbClick(SDL_MouseButtonEvent &evt)
{
    SDL_Log("dbclick");
}
